package com.shqcjd.preinstallmobile.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.horen.chart.barchart.BarChartHelper;
import com.horen.chart.barchart.IBarData;
import com.horen.chart.piechart.IPieData;
import com.horen.chart.piechart.PieChartHelper;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.model.eventbus.GoGuideEvent;
import com.shqcjd.preinstallmobile.model.eventbus.GoInspectionEvent;
import com.shqcjd.preinstallmobile.model.eventbus.IndexAllEvent;
import com.shqcjd.preinstallmobile.model.eventbus.RefreshReddotEvent;
import com.shqcjd.preinstallmobile.model.eventbus.ShowGuideEvent;
import com.shqcjd.preinstallmobile.model.eventbus.ShowInspectionEvnent;
import com.shqcjd.preinstallmobile.model.pojo.EqptBarData;
import com.shqcjd.preinstallmobile.model.pojo.EqptPieData;
import com.shqcjd.preinstallmobile.model.pojo.IndexBean;
import com.shqcjd.preinstallmobile.model.pojo.MenuEntity;
import com.shqcjd.preinstallmobile.ui.activity.DefectManageActivity;
import com.shqcjd.preinstallmobile.ui.activity.EquipmentInfoActivity;
import com.shqcjd.preinstallmobile.ui.activity.EquipmentListActivity;
import com.shqcjd.preinstallmobile.ui.activity.ExpertDetailActivity;
import com.shqcjd.preinstallmobile.ui.activity.ExpertListActivity;
import com.shqcjd.preinstallmobile.ui.activity.HeadlineNewsActivity;
import com.shqcjd.preinstallmobile.ui.activity.MessageListActivity;
import com.shqcjd.preinstallmobile.ui.activity.NewsDetailActivity;
import com.shqcjd.preinstallmobile.ui.activity.ProcessBackActivity;
import com.shqcjd.preinstallmobile.ui.activity.QRcodeActivity;
import com.shqcjd.preinstallmobile.ui.adapter.BannerImageLoader;
import com.shqcjd.preinstallmobile.ui.adapter.EqptStateAdapter;
import com.shqcjd.preinstallmobile.ui.adapter.HeadlinesAdapter;
import com.shqcjd.preinstallmobile.ui.adapter.HorizontalExpertAdapter;
import com.shqcjd.preinstallmobile.ui.adapter.MenuAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseFragment;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.SpacesItemDecoration;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

/**
 * 首页
 * Created by sy on 2019/3/14.
 */

public class HomeFragment extends BaseFragment {
    private static final int REQUEST_CODE = 1000;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rv_menu_list)
    RecyclerView rv_menu_list;
    @BindView(R.id.rv_headlines)
    RecyclerView rv_headlines;
    @BindView(R.id.single_bar_chart)
    BarChart single_bar_chart;
    @BindView(R.id.pie_chart)
    PieChart pie_chart;
    @BindView(R.id.rv_eqpt_state)
    RecyclerView rv_eqpt_state;
    @BindView(R.id.rv_expert)
    RecyclerView rv_expert;
    @BindView(R.id.tv_more_news)
    TextView tvMoreNews;
    @BindView(R.id.tv_more_expert)
    TextView tvMoreExpert;
    @BindView(R.id.iv_news)
    ImageView iv_news;
    @BindView(R.id.iv_scan)
    ImageView iv_scan;
    @BindView(R.id.ll_news_layout)
    LinearLayout ll_news_layout;
    @BindView(R.id.ll_chart_layout)
    LinearLayout ll_chart_layout;
    @BindView(R.id.ll_eqpt_state_layout)
    LinearLayout ll_eqpt_state_layout;
    @BindView(R.id.ll_expert_layout)
    LinearLayout ll_expert_layout;
    @BindView(R.id.iv_reddot)
    ImageView iv_reddot;
    @BindView(R.id.ll_search)
    LinearLayout ll_search;
    @BindView(R.id.tv_more_equipment)
    TextView tv_more_equipment;

    private List<String> mMenuList;

    List<MenuEntity> mMenuEntityList = new ArrayList<>();
    static final Integer[] iconimgs = new Integer[]{
            R.mipmap.xjxt, R.mipmap.qxgl, R.mipmap.yczd, R.mipmap.txhf, R.mipmap.sbgl};
    private MenuAdapter menuAdapter;



    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @Override
    public void initView(View rootView) {
        EventBus.getDefault().register(this);//订阅
        //轮播图
        initBanner();

    }

    @Override
    public void initData() {
        isHasMsg();
        setTimer();
    }

    /**
     * 专家指导
     * @param expert
     */
    private void initExpert(List<IndexBean.ExpertBean> expert) {
        HorizontalExpertAdapter horizontalExpertAdapter = new HorizontalExpertAdapter(expert);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rv_expert.setLayoutManager(linearLayoutManager);
        rv_expert.setAdapter(horizontalExpertAdapter);
        //添加ItemDecoration，item之间的间隔
        int leftRight = UIUtils.dip2px(3);
        int topBottom = UIUtils.dip2px(0);
        int padding = UIUtils.dip2px(10);
        rv_expert.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom, true, padding));
        horizontalExpertAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexBean.ExpertBean item = (IndexBean.ExpertBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), ExpertDetailActivity.class);
                intent.putExtra("ExpertId", item.id);
                startActivity(intent);
            }
        });


    }

    /**
     *  设备实时状态
     * @param equipment_state
     */
    private void initEqptState(List<IndexBean.EquipmentStateBean> equipment_state) {

        EqptStateAdapter eqptStateAdapter = new EqptStateAdapter(equipment_state);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rv_eqpt_state.setLayoutManager(linearLayoutManager);
        rv_eqpt_state.setAdapter(eqptStateAdapter);
        //添加ItemDecoration，item之间的间隔
        int leftRight = UIUtils.dip2px(10);
        int topBottom = UIUtils.dip2px(0);
        rv_eqpt_state.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
        eqptStateAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexBean.EquipmentStateBean item = (IndexBean.EquipmentStateBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), EquipmentInfoActivity.class);
                intent.putExtra("kks", item.kks);
                startActivity(intent);
            }
        });

    }

    /**
     * 显示图表
     * @param handle
     */
    private void initChart(IndexBean.HandleBean handle) {
        initSingleBarChart(handle.equipment_type);
        initPieChart(handle.rate);

    }

    /**
     * 饼状图
     * @param rate
     */
    private void initPieChart(List<IndexBean.HandleBean.RateBean> rate) {
        ArrayList<IPieData> entries = new ArrayList<>();
        for (IndexBean.HandleBean.RateBean bean : rate) {
            entries.add(new EqptPieData(bean.value,bean.name));
        }
        List<Integer> mPieColors = new ArrayList<>();
        mPieColors.add(Color.parseColor("#FCCF01"));
        mPieColors.add(Color.parseColor("#275BC0"));
        new PieChartHelper.Builder()
                // 上下文
                .setContext(getContext())
                // 饼图
                .setPieChart(pie_chart)
                // 绑定数据
                .setPieData(entries)
                // Label颜色
                .setLableTextColor(Color.WHITE)
                .setLableTextSize(8)
                // 饼图内标签文字
                .setDrawEntryLabels(true)
                // 动画时间
                .setDurationMillis(2000)
                // 动画类型
                .setEasing(Easing.EasingOption.EaseInOutQuad)
                // 旋转角度
                .setRawRotationAngle(90)
                // 中心图表孔旁边的透明圆的半径
                .setTransparentCircleRadiusPercent(10f)
                // 饼图Item被选中时变化的距离
                .setSelectionShift(5f)
                // 饼图区块之间的距离
                .setSliceSpace(1f)
                // 中心空白圆心大小
                .setHoleRadiusPercent(40f)
                .setPieColors(mPieColors)
                // 是否开启标签
                .setLegendEnable(true)
                .build();
    }


    /**
     * 柱状图
     * @param equipment_type
     */
    private void initSingleBarChart(List<IndexBean.HandleBean.EquipmentTypeBean> equipment_type) {
        //模拟数据
        ArrayList<IBarData> entries = new ArrayList<>();
        for (IndexBean.HandleBean.EquipmentTypeBean bean : equipment_type) {
            entries.add(new EqptBarData(bean.value, bean.name));
        }
        //创建多条折线的图表
        new BarChartHelper.Builder()
                .setContext(getContext())
                .setBarChart(single_bar_chart)
                .setBarData(entries)
                // 一页X轴显示个数
                .setDisplayCount(6)
                // 标签显示隐藏
                .setLegendEnable(false)
                // 标签文字大小
                .setLegendTextSize(20)
                // 是否显示右边Y轴
                .setyAxisRightEnable(false)
                // X,Y轴是否绘制网格线
                .setDrawGridLines(false)
                // 缩放
                .setScaleEnabled(false)
                // 是否可以通过双击屏幕放大图表
                .setDoubleTapToZoomEnabled(false)
                // 柱状图描述 图表右下角
                .setDescriptionEnable(false)
                // 按比例放缩柱状图
                .setPinchZoom(true)
                // 单柱状图 每个柱的宽度，只在单柱状图生效
                .setBarWidth(0.6f)
                // x,y轴动画时间和类型
                .setDurationMillis(2000)
                .setEasing(Easing.EasingOption.Linear)
                // 单柱状图颜色
                .setBarColor(Color.parseColor("#275bc0"))
                // X轴是否显示自定义数据，在IBarData接口中定义
                .setXValueEnable(true)
                .build();
    }

    /**
     * 头条新闻
     * @param news
     */
    private void initHeadlines(List<IndexBean.NewsBean> news) {
        HeadlinesAdapter headlinesAdapter = new HeadlinesAdapter(news);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rv_headlines.setLayoutManager(linearLayoutManager);
        rv_headlines.setAdapter(headlinesAdapter);
        //添加ItemDecoration，item之间的间隔
        int leftRight = UIUtils.dip2px(10);
        int topBottom = UIUtils.dip2px(0);
        rv_headlines.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
        headlinesAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexBean.NewsBean item = (IndexBean.NewsBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), NewsDetailActivity.class);
                intent.putExtra("newsId", item.id);
                startActivity(intent);
            }
        });
    }

    /**
     *  判断集合是否包含某属性
     * @return
     */
    private Boolean isContains(String string, List<MenuEntity> list) {
        for (MenuEntity bean : list) {
            if (bean.name.equals(string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 菜单列表
     * @param childs
     */
    private void initMenu(List<IndexBean.MenusBean.ChildsBean> childs) {
//        mMenuList = Arrays.asList(getResources().getStringArray(R.array.home_menu));
        mMenuEntityList.clear();
        for (int i = 0; i < childs.size(); i++) {
            MenuEntity mMenuBean = new MenuEntity();
            mMenuBean.url = childs.get(i).current.icon;
            mMenuBean.name = childs.get(i).current.menu_name;

            mMenuEntityList.add(mMenuBean);
        }

        //判断是否显示巡检模块
        if (isContains("巡检系统",mMenuEntityList)) {
            EventBus.getDefault().post(new ShowInspectionEvnent(true));
        } else {
            EventBus.getDefault().post(new ShowInspectionEvnent(false));
        }

        //判断app是否显示专家模块
        if (isContains("远程指导",mMenuEntityList)) {
            EventBus.getDefault().post(new ShowGuideEvent(true));
        } else {
            EventBus.getDefault().post(new ShowGuideEvent(false));
        }

        //布局管理器对象 参数1.上下文 2.规定一行显示几列的参数常量
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), childs.size());
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        rv_menu_list.setLayoutManager(gridLayoutManager);
        menuAdapter = new MenuAdapter(mMenuEntityList);
        rv_menu_list.setAdapter(menuAdapter);
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MenuEntity menuEntity = (MenuEntity) adapter.getData().get(position);
                Intent it;
                //根据点击不同菜单跳转
                switch (menuEntity.name) {
                    case "巡检系统":
                        EventBus.getDefault().post(new GoInspectionEvent());
                        break;
                    case "缺陷管理":
                        it= new Intent(getActivity(), DefectManageActivity.class);
                        startActivity(it);
                        break;
                    case "远程指导":
                        EventBus.getDefault().post(new GoGuideEvent());
                        break;
                    case "图像回放":
                        it= new Intent(getActivity(), ProcessBackActivity.class);
                        startActivity(it);
                        break;
                    case "设备管理":
                        it = new Intent(getActivity(), EquipmentListActivity.class);
                        startActivity(it);
                        break;
                }
            }
        });


    }

    private void initBanner() {
        //资源文件
        final List<Integer> images = new ArrayList<>();
        images.add(R.mipmap.ic_muxian);
        images.add(R.mipmap.ic_bianyaqi3);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置图片集合
        banner.setImages(images);
        banner.start();
    }

    /**
     * 判断是否有未读消息
     */
    private void isHasMsg(){
//        ApiService.unread()
//                .compose(RxSchedulersHelper.io_main())
//                .subscribe(new RxObserver<ResponseData<Integer>>() {
//                    @Override
//                    public void _onNext(ResponseData<Integer> retData) {
//                        if (retData.retCode == 10000) {
//                            if (retData.data > 0) {
//                                iv_reddot.setVisibility(View.VISIBLE);
//                            } else {
//                                iv_reddot.setVisibility(View.GONE);
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void _onError(String errorMessage) {
//
//                    }
//                });
    }

    /**
     * 当收到后台消息的时候显示，显示红点
     * @param event
     */
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void refreshReddot(RefreshReddotEvent event) {
        if (event.isShow) {
            iv_reddot.setVisibility(View.VISIBLE);
        } else {
            iv_reddot.setVisibility(View.GONE);
        }
    }

    /**
     * 获取首页内容
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getIndexAll(IndexAllEvent event) {
        showModule(event.indexBean);
    }



    /**
     * 显示功能模块
     * @param indexBean
     */
    private void showModule(IndexBean indexBean) {
        rv_menu_list.setVisibility(View.GONE);
        ll_news_layout.setVisibility(View.GONE);
        ll_chart_layout.setVisibility(View.GONE);
        ll_eqpt_state_layout.setVisibility(View.GONE);
        ll_expert_layout.setVisibility(View.GONE);
        EventBus.getDefault().post(new ShowInspectionEvnent(false));
        EventBus.getDefault().post(new ShowGuideEvent(false));
        for (IndexBean.MenusBean menu : indexBean.menus) {
            switch (menu.value) {
                case "NAVICATION"://菜单列表
                    rv_menu_list.setVisibility(View.VISIBLE);
                    initMenu(menu.childs);
                    break;
                case "NEWS"://头条新闻
                    ll_news_layout.setVisibility(View.VISIBLE);
                    initHeadlines(indexBean.news);
                    break;
                case "HANDLED"://消缺率
                    ll_chart_layout.setVisibility(View.VISIBLE);
                    initChart(indexBean.handle);
                    break;
                case "EQUIPMENT"://设备实时状态
                    ll_eqpt_state_layout.setVisibility(View.VISIBLE);
                    initEqptState(indexBean.equipment_state);
                    break;
                case "EXPERT"://专家列表
                    ll_expert_layout.setVisibility(View.VISIBLE);
                    initExpert(indexBean.expert);
                    break;
            }
        }

    }


    @OnClick({R.id.tv_more_news, R.id.tv_more_expert,R.id.iv_news,R.id.iv_scan,R.id.ll_search,R.id.tv_more_equipment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_more_news://更多头条新闻
                startActivity(new Intent(getContext(), HeadlineNewsActivity.class));
                break;
            case R.id.tv_more_expert://更多专家
                startActivity(new Intent(getContext(), ExpertListActivity.class));
                break;
            case R.id.iv_news://消息
                startActivity(new Intent(getContext(), MessageListActivity.class));
                break;
            case R.id.iv_scan://扫码
                RxPermissions permissions = new RxPermissions(getActivity());
                permissions.setLogging(true);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    startActivityForResult(new Intent(getActivity(), QRcodeActivity.class),REQUEST_CODE);
                                } else {
                                    ToastUtils.show(getContext(), "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });

                break;
            case R.id.ll_search://搜索设备
                startActivity(new Intent(getContext(), EquipmentListActivity.class));
                break;
            case R.id.tv_more_equipment://更多设备
                startActivity(new Intent(getContext(), EquipmentListActivity.class));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            Log.i("二维码", "onActivityResult: 返回值"+value);
            Intent intent = new Intent(getContext(), EquipmentInfoActivity.class);
            intent.putExtra("kks", value);
            startActivity(intent);


        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解除订阅
        stopTimer();
    }

    private static final int TIMER = 999;
    private void setTimer(){
        timer.schedule(task, 1000, 5000);       // timeTask
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TIMER:
                    //在此执行定时操作
                    isHasMsg();
                    break;
                default:
                    break;
            }
        }
    };

    Timer timer = new Timer();

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(TIMER);
        }
    };

    private void stopTimer(){
        timer.cancel();
        task.cancel();
    }

}
